import React, { useEffect, useState } from 'react';
import { TjCollapse, TjFilter, TjHeader, TjSlideSelect } from '@/tjComponents';
// @ts-ignore
import TjDimension from '@/pages/ETrade/components/TjFrom/TjDimension';
import { useForm } from 'antd/lib/form/Form';
import './index.less';
import { dimensionOptions, dimensionOptionsKeys } from './helper';
// @ts-ignore
import { Button, DatePicker, Select, Radio, message, Space } from 'antd';
import { connect } from 'umi';
import { useRequestPowerAfterInit } from '@/hooks/useRequestPowerAfterInit';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import type { ProvinceType, StationType } from '@/hooks/useRequestPowerAfterInit';
import moment from 'moment';
import IncomeDeviationCharts from './components/IncomeDeviationCharts';
import QuantityPriceCharts from './components/QuantityPriceCharts';
import _ from 'lodash';
import { HttpCode } from '#/utils/contacts';
import { api_getFlexData } from './services';
import { features, useTablePipeline } from 'ali-react-table';
import { TjStation, TjTable, useStaticState, useTRState } from '@/pages/ETrade/components';
import { TIME_96, TIME_24 } from '@/pages/ETrade/components/helper.js';
import { PageLoading } from '@/components';

const { RangePicker } = DatePicker;

const initFilterValue = {
  time: [moment().startOf('month'), moment()],
  timeOrder: 24,
  tag: 1,
  order: ['stationName', 'date'],
};

const index: React.FC<IindexProps> = (props) => {
  const { initLoading, province, errorMsg, treeData } = useRequestPowerAfterInit(
    '/power/dataPower/common/StationTradeParamConfig/t_station',
    (parmas) => {
      const stations = {},
        stationIds = [];
      parmas.stations.forEach((v: StationType) => {
        stations[v.stationId] = {
          value: v.stationId,
          label: v.stationName,
        };
        stationIds.push(v.stationId);
      });
      const obj = {
        stations,
        stationIds,
        marketId: parmas.value,
        ...initFilterValue,
      };
      setCurrentProvinceInfo(parmas);
      setDefaultValues(obj);
      onInit(obj);
    },
    {
      convertResult: '2',
      matchFirst: 0,
    },
  );
  const [defaultValues, setDefaultValues] = useState<any>();
  const [currentProvinceInfo, setCurrentProvinceInfo] = useState<ProvinceType>();
  const [loading, setLoading] = useState<boolean>(true);
  const [state, setState] = useTRState({
    selectValues: {},
    columns: [],
    columnsKeys: [],
    dataSource: [],
    dimensionVal: ['交易单元', '日期'],
    stations: {},
    dimensionKeys: initFilterValue.order,
    filters: {
      stationName: '',
      date: '',
      timeOrder: '',
    },
  });
  const staticState = useStaticState({
    tableColumns: [],
    dataSourceObj: {},
    time96: TIME_96.map((v) => {
      return {
        label: v,
        value: v,
      };
    }),
    time24: TIME_24.map((v) => {
      return {
        label: v,
        value: v,
      };
    }),
    dimensionKeys: initFilterValue.order,
    filterOptions: {},
    filters: {
      stationName: '',
      date: '',
      timeOrder: '',
    },
    xAxisData1: [],
    xAxisData2: [],
  });
  const [form] = useForm();

  const onSearch = (values: any) => {
    setLoading(true);
    staticState.dimensionKeys = state.dimensionKeys;
    staticState.filters = {
      stationName: values.stationIds?.[0] || '',
      date: values?.time?.length ? moment(values.time[0]) : null,
      timeOrder:
        values.timeOrder === 24 ? staticState.time24[0].label : staticState.time96[0].label,
    };
    const filterDatas = {
      ...values,
      order: state.dimensionKeys,
    };
    setState({
      selectValues: filterDatas,
      filters: staticState.filters,
    });
    query(filterDatas);
  };

  const onReset = (values: any) => {
    setLoading(true);
    const item = _.find(province, (n: ProvinceType) => n.value === values.marketId);

    staticState.dimensionKeys = state.dimensionKeys;
    staticState.filters = {
      stationName: values.stationIds?.[0] || '',
      date: values?.time?.length ? moment(values.time[0]) : null,
      timeOrder:
        values.timeOrder === 24 ? staticState.time24[0].label : staticState.time96[0].label,
    };
    setState({
      selectValues: defaultValues,
      filters: staticState.filters,
      stations: defaultValues.stations || {},
    });
    if (item) {
      setCurrentProvinceInfo(item);
    }
    form.setFieldsValue({
      ...defaultValues,
    });
    query(defaultValues);
  };

  const changeMarketId = (val: string) => {
    const item = _.find(province, (n: ProvinceType) => n.value === val);
    if (item) {
      const stations = {},
        stationIds = [];
      item.stations.forEach((v: StationType) => {
        stations[v.stationName] = {
          value: v.stationId,
          label: v.stationName,
        };
        stationIds.push(v.stationId);
      });
      setCurrentProvinceInfo(item);
      setState({
        stations,
      });
      form.setFieldsValue({
        stationIds,
      });
    }
  };

  const aggregation = () => {
    setLoading(true);

    staticState.dimensionKeys = state.dimensionKeys;
    staticState.filters = {
      stationName: state.selectValues.stationIds?.[0] || '',
      date: state.selectValues?.time?.length ? moment(state.selectValues.time[0]) : null,
      timeOrder:
        state.selectValues.timeOrder === 24
          ? staticState.time24[0].label
          : staticState.time96[0].label,
    };

    const filterDatas = {
      ...state.selectValues,
      order: state.dimensionKeys,
    };
    setState({
      filters: staticState.filters,
    });
    query(filterDatas);
  };

  const getQueryParmas = (data: any) => {
    const param: any = {
      marketId: data.marketId,
      stationIds: data.stationIds,
      tag: data.tag,
    };
    if (data.time && data.time.length > 0) {
      param.startDate = moment(data.time[0]).format('YYYY-MM-DD');
      param.endDate = moment(data.time[1]).format('YYYY-MM-DD');
    }
    return {
      flexAggrBody: {
        headType: 2,
        timeOrder: data.timeOrder,
        order: state.dimensionKeys,
        cacheable: true,
        needTotal: true,
      },
      param,
    };
  };

  const tileTree = (values = {}) => {
    const {
      currentData,
      parentData,
      parentDataObj,
      keys,
      data,
      dataObj,
      type,
      treeNum,
      filterValues,
    } = values;

    Object.keys(currentData).forEach((value) => {
      const id = `${parentData?.id || ''}${value}`;
      const isStart = type === 'start',
        order =
          isStart && value === 'total'
            ? '合计'
            : staticState.dimensionKeys[treeNum - 1] === 'timeOrder'
            ? filterValues?.timeOrder === 24
              ? TIME_24[value - 1]
              : TIME_96[value - 1]
            : value;
      const obj = { order, children: [], id },
        obj1 = { order, data: [] };

      if (isStart || value !== 'total') {
        if (_.isArray(currentData[value])) {
          currentData[value].forEach((val, ind) => {
            obj[keys[ind]] = val;
            obj1.data.push(val);
          });
          data.push(obj);
          dataObj[order] = obj1;
        } else {
          tileTree({
            filterValues,
            treeNum: treeNum + 1,
            currentData: currentData[value],
            parentData: obj,
            parentDataObj: obj1,
            keys,
            dataObj: obj1,
            data: obj.children,
            type: '',
          });
          data.push(obj);
          dataObj[order] = obj1;
        }
      } else {
        currentData[value].forEach((val, ind) => {
          parentData[keys[ind]] = val;
          parentDataObj.data.push(val);
        });
      }
    });
  };

  const query = (values = {}) => {
    const newReq = getQueryParmas(values);

    api_getFlexData(newReq).then((res: any) => {
      if (res.statusCode === HttpCode.SUCCESS) {
        const columns = [],
          columnsKeys = [],
          tableData = [],
          tableDataObj = {},
          treeNum = 1;

        res?.data?.head?.forEach((v) => {
          columns.push({
            ...v,
            code: v.field || '',
            align: 'center',
            width: 100,
          });
          columnsKeys.push(v.field);
        });
        staticState.tableColumns = res?.data?.head || [];
        tileTree({
          filterValues: values,
          treeNum,
          currentData: res?.data?.data || {},
          keys: columnsKeys || [],
          data: tableData,
          dataObj: tableDataObj,
          type: 'start',
        });
        staticState.dataSourceObj = tableDataObj;
        setState({
          dataSource: tableData,
          columns: [].concat(
            [
              {
                name: '聚合纬度',
                field: 'order',
                code: 'order',
                align: 'center',
                width: 130,
              },
            ],
            columns,
          ),
          columnsKeys,
        });
      }
      setLoading(false);
    });
  };

  const onInit = (values = {}) => {
    staticState.filters = {
      stationName: values.stationIds?.[0] || '',
      date: values?.time?.length ? moment(values.time[0]) : null,
      timeOrder:
        values.timeOrder === 24 ? staticState.time24[0].label : staticState.time96[0].label,
    };

    setState({
      stations: values.stations || {},
      filters: staticState.filters,
    });
    query(values);
  };

  const filterOption = (input: string, option: { value: any; label: any }) => {
    const { value, label } = option;
    return (
      value?.toLowerCase().indexOf(input.toLowerCase()) >= 0 ||
      label?.toLowerCase().indexOf(input.toLowerCase()) >= 0
    );
  };

  const pipeline = useTablePipeline({ components: {} })
    .input({ dataSource: state.dataSource, columns: state.columns || [] })
    .primaryKey('id')
    .use(features.treeMode());

  return (
    <div className="jsfp">
      <TjHeader
        left={
          <TjFilter
            defaultValues={defaultValues}
            onReset={onReset}
            onSearch={onSearch}
            loading={loading}
            form={form}
            items={[
              {
                name: 'marketId',
                render: (
                  <Select
                    allowClear={false}
                    showSearch={true}
                    filterOption={filterOption}
                    options={province}
                    style={{ width: 180 }}
                    loading={initLoading}
                    onChange={changeMarketId}
                  />
                ),
              },
              {
                name: 'stationIds',
                render: (
                  <TjMarketingUnit
                    treeData={treeData}
                    marketId={currentProvinceInfo?.value}
                    onChange={(ids = [], list = []) => {
                      const newStations = {};
                      list.forEach((v: StationType) => {
                        newStations[v.key] = {
                          value: v.key,
                          label: v.title,
                        };
                      });
                      setState({
                        stations: newStations,
                      });
                    }}
                  />
                ),
              },
              {
                name: 'time',
                render: <RangePicker allowClear={false} />,
              },
              {
                name: 'timeOrder',
                render: (
                  <TjSlideSelect
                    items={[
                      { label: '24', value: 24 },
                      { label: '96', value: 96 },
                    ]}
                  />
                ),
              },
              {
                name: 'tag',
                render: (
                  <TjSlideSelect
                    items={[
                      { label: '测算数据', value: 1 },
                      { label: '结算数据', value: 2 },
                    ]}
                  />
                ),
              },
            ]}
          />
        }
      />
      <TjCollapse
        leftContent={
          <div className="left-content">
            <div className="title">基数复盘数据</div>
            <TjDimension
              value={state.dimensionVal}
              options={dimensionOptions}
              loading={loading}
              onChange={(order: any[]) => {
                const orderKeys = [];
                order.forEach((o) => {
                  orderKeys.push(dimensionOptionsKeys[o]);
                });
                setState({
                  dimensionKeys: orderKeys,
                  dimensionVal: order,
                });
              }}
              onPoly={aggregation}
            />
            <div className="table-box">
              <TjTable isLoading={loading} {...pipeline.getProps()} />
            </div>
          </div>
        }
        rightContent={
          loading ? (
            <PageLoading />
          ) : (
            <div className="right-content">
              <div className="filter_group">
                <div className="flex">
                  <Space size={16}>
                    {staticState.dimensionKeys.slice(0, -1).map((v) => {
                      if (v === 'stationName') {
                        return (
                          <Select
                            key={v}
                            allowClear={false}
                            style={{ minWidth: 140 }}
                            value={state.filters[v]}
                            options={Object.values(state.stations)}
                            optionFilterProp="label"
                            onChange={(id) =>
                              setState({ filters: { ...state.filters, stationName: id } })
                            }
                            showSearch
                          />
                        );
                      }
                      if (v === 'date') {
                        return (
                          <DatePicker
                            allowClear={false}
                            key={v}
                            value={state.filters[v]}
                            style={{ minWidth: 140 }}
                            onChange={(date) => setState({ filters: { ...state.filters, date } })}
                          />
                        );
                      }
                      if (v === 'timeOrder') {
                        return (
                          <Select
                            allowClear={false}
                            key={v}
                            style={{ minWidth: 140 }}
                            value={state.filters[v]}
                            options={
                              state.filters[v] === '0015' ? staticState.time96 : staticState.time24
                            }
                            onChange={(id) =>
                              setState({ filters: { ...state.filters, timeOrder: id } })
                            }
                            showSearch
                          />
                        );
                      }
                    })}
                  </Space>
                </div>
              </div>
              <div className="item">
                <div className="title">模拟A与实际B量价对比</div>
                <QuantityPriceCharts
                  data={staticState.dataSourceObj}
                  filters={state.filters}
                  dimensionKeys={staticState.dimensionKeys}
                  stations={state.stations}
                  tableColumns={staticState.tableColumns}
                />
              </div>
              <div className="item">
                <div className="title">模拟A与实际B收入偏差对比</div>
                <IncomeDeviationCharts
                  data={staticState.dataSourceObj}
                  filters={state.filters}
                  dimensionKeys={staticState.dimensionKeys}
                  stations={state.stations}
                  tableColumns={staticState.tableColumns}
                />
              </div>
            </div>
          )
        }
      />
    </div>
  );
};

interface IindexProps {
  menuCode: string;
}

export default connect(({ global }: any) => ({
  menuCode: global.configure.menuCode,
}))(index);
